package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.entity.OrderRun;
import com.woniuxy.entity.DTO.OrderRunQueryDTO;
import com.woniuxy.mapper.OrderRunMapper;
import com.woniuxy.service.IOrderRunService;
import com.woniuxy.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author pml
 * @Date 2025/7/16 19:27
 * @Description TODO
 * 跑腿订单服务实现类
 * 实现订单相关的业务逻辑
 * 复用UserServiceImpl的分页查询逻辑，保持代码风格一致
 */
@Service
public class OrderRunServiceImpl extends ServiceImpl<OrderRunMapper, OrderRun> implements IOrderRunService {

    @Autowired
    private OrderRunMapper orderRunMapper;

    /**
     * 分页多条件查询订单列表
     * 使用MyBatis-Plus的分页插件和条件构造器实现复杂查询
     * 支持多条件组合查询，满足不同业务场景需求
     */
    @Override
    public PageResult<OrderRun> getOrderRunList(OrderRunQueryDTO queryDTO) {
        // 创建分页对象，设置当前页码和每页数量
        Page<OrderRun> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 创建查询条件构造器
        QueryWrapper<OrderRun> queryWrapper = new QueryWrapper<>();

        // 订单编号模糊查询
        if (queryDTO.getOrderNumber() != null && !queryDTO.getOrderNumber().isEmpty()) {
            queryWrapper.like("order_number", queryDTO.getOrderNumber());
        }

        // 发帖人ID精确查询
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq("user_id", queryDTO.getUserId());
        }

        // 接单者ID精确查询
        if (queryDTO.getTakeUserId() != null) {
            queryWrapper.eq("take_user_id", queryDTO.getTakeUserId());
        }

        // 订单状态精确查询
        if (queryDTO.getOrderStatus() != null) {
            queryWrapper.eq("order_status", queryDTO.getOrderStatus());
        }

        // 创建时间范围查询
        if (queryDTO.getCreateTimeStart() != null) {
            queryWrapper.ge("create_time", queryDTO.getCreateTimeStart());
        }
        if (queryDTO.getCreateTimeEnd() != null) {
            queryWrapper.le("create_time", queryDTO.getCreateTimeEnd());
        }

        // 按创建时间降序排序，最新订单优先展示
        queryWrapper.orderByDesc("create_time");

        // 执行分页查询，MyBatis-Plus自动处理count和分页逻辑
        IPage<OrderRun> orderRunPage = orderRunMapper.selectPage(page, queryWrapper);

        // 将MyBatis-Plus分页结果转换为自定义PageResult
        PageResult<OrderRun> pageResult = new PageResult<>();
        pageResult.setPageNum(queryDTO.getPageNum());
        pageResult.setPageSize(queryDTO.getPageSize());
        pageResult.setTotal(orderRunPage.getTotal());
        pageResult.setPages((int) orderRunPage.getPages());
        pageResult.setList(orderRunPage.getRecords());

        return pageResult;
    }

    /**
     * 批量更新订单状态
     * 用于批量操作（如批量取消），提高系统操作效率
     * 使用update方法而非remove方法，实现逻辑删除
     */
    @Override
    public boolean batchUpdateStatus(List<Integer> ids, Integer status) {
        if (ids == null || ids.isEmpty() || status == null) {
            return false;
        }
        // 创建更新条件
        QueryWrapper<OrderRun> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);

        // 创建更新对象
        OrderRun updateOrder = new OrderRun();
        updateOrder.setOrderStatus(status);

        // 执行批量更新
        return this.update(updateOrder, queryWrapper);
    }


    @Override
    public Map<Integer, Integer> getOrderStatusDistribution() {
        QueryWrapper<OrderRun> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("state, count(*) as count");
        queryWrapper.groupBy("state");

        List<Map<String, Object>> maps = orderRunMapper.selectMaps(queryWrapper);
        Map<Integer, Integer> distribution = new HashMap<>();

        for (Map<String, Object> map : maps) {
            Integer state = (Integer) map.get("state");
            Long count = (Long) map.get("count");
            distribution.put(state, count.intValue());
        }

        return distribution;
    }

    @Override
    public Long getTotalOrderCount() {
        return orderRunMapper.selectCount(null);
    }
}